﻿using SmartMotion.AllPages.DockPanels;
using SmartMotion.Core;
using Sunny.UI;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using EventMgrLib;
using Unity;
using WeifenLuo.WinFormsUI.Docking;

namespace SmartMotion.AllPages
{
    public partial class FrmFlowEdit : UIPage
    {
        #region 私有字段

        private string _configFile;
        private DeserializeDockContent _deserializeDockContent;
        private EventMgr _em;
        private IUnityContainer _container;
        private ActionItem _currentActionItem;
        private Flow _currentFlow;
        #endregion

        #region 构造和Load

        public FrmFlowEdit()
        {
            InitializeComponent();
        }

        private void FrmFlowEdit_Load(object sender, EventArgs e)
        {
            _container = UnityIoc.Ins.Container;
            _em = EventMgr.Ins;
            LoadIdeConfig();
            _em.GetEvent<ExitApp>().Subscribe(SaveConfig);
            _em.GetEvent<ShowIdeWindow>().Subscribe(ShowWindow);
            _em.GetEvent<ShowEditFrm>().Subscribe(ShowEditPanel);
            _em.GetEvent<SelectActionChanged>().Subscribe(ActionChanged);
            _em.GetEvent<GlobalControlEvent>().Subscribe(EditRun);
        }

        private void EditRun(Controller controller)
        {
            Task.Factory.StartNew(() =>
            {
                if (controller == Controller.RunRow)
                {
                    _currentActionItem?.Run();
                }

                if (controller == Controller.RunFlow)
                {
                    _currentFlow?.Run();
                }
            });

        }

        private void ActionChanged(ActionItem item)
        {
            _currentActionItem = item;
        }

        #endregion  

        #region 停靠面板布局

        private void LoadIdeConfig()
        {
            #region 初始化停靠面板

            dockPanel1.Theme = new VS2015BlueTheme();


            try
            {
                //加载配置
                _deserializeDockContent = GetContentFromPersistString;
                _configFile = Path.Combine(Path.GetDirectoryName(Application.ExecutablePath), "DockPanel.config");
                if (File.Exists(_configFile))
                {
                    dockPanel1.LoadFromXml(_configFile, _deserializeDockContent);
                }
            }
            catch (Exception)
            {
                DefaultLayout();
            }

            #endregion
        }

        private IDockContent GetContentFromPersistString(string persistString)
        {
            if (persistString == typeof(FrmToolBox).ToString())
                return _container.Resolve<FrmToolBox>();
            if (persistString == typeof(FrmSolutionMgr).ToString())
                return _container.Resolve<FrmSolutionMgr>();
            if (persistString == typeof(FrmProperty).ToString())
                return _container.Resolve<FrmProperty>();
            if (persistString == typeof(FrmVar).ToString())
                return _container.Resolve<FrmVar>();
            if (persistString == typeof(FrmParms).ToString())
                return _container.Resolve<FrmParms>();
            if (persistString == typeof(FrmDebug).ToString())
                return _container.Resolve<FrmDebug>();
            //if (persistString == typeof(FrmEdit).ToString())
            //    return _container.Resolve<FrmEdit>();
            return null;
        }

        private void ShowWindow(string window)
        {
            switch (window)
            {
                case "默认布局":
                    DefaultLayout();
                    break;
                case "工具箱":
                    var toolBox = _container.Resolve<FrmToolBox>();
                    toolBox.Show(dockPanel1);
                    break;
                case "资源管理器":
                    var frmSolutionMgr = _container.Resolve<FrmSolutionMgr>();
                    frmSolutionMgr.Show(dockPanel1, DockState.DockRight);
                    break;
                case "属性":
                    var frmProperty = _container.Resolve<FrmProperty>();
                    frmProperty.Show(dockPanel1, DockState.DockRight);
                    break;
                case "调试":
                    var frmDebug = _container.Resolve<FrmDebug>();
                    frmDebug.Show(dockPanel1, DockState.DockBottom);
                    break;
                case "参数":
                    var frmParms = _container.Resolve<FrmParms>();
                    frmParms.Show(dockPanel1, DockState.DockBottom);
                    break;
                case "变量":
                    var frmVar = _container.Resolve<FrmVar>();
                    frmVar.Show(dockPanel1);
                    break;
            }   
        }

        private void DefaultLayout()
        {
            var toolBox = _container.Resolve<FrmToolBox>();
            toolBox.Show(dockPanel1, DockState.DockLeft);
            dockPanel1.DockLeftPortion = 240;

            var frmSolutionMgr = _container.Resolve < FrmSolutionMgr>();
            frmSolutionMgr.Show(dockPanel1, DockState.DockRight);
            dockPanel1.DockRightPortion = 240;

            var frmProperty = _container.Resolve < FrmProperty>();
            frmProperty.Show(dockPanel1, DockState.DockRight);
            
            var frmEdit = _container.Resolve < FrmFLowChartEdit>();
            frmEdit.Show(dockPanel1);

           

            var frmVar = _container.Resolve < FrmVar>();
            frmVar.Show(dockPanel1);

            var frmParms = _container.Resolve < FrmParms>();
            frmParms.Show(dockPanel1, DockState.DockBottom);
            dockPanel1.DockBottomPortion = 240;

            var frmDebug = _container.Resolve < FrmDebug>();
            frmDebug.Show(dockPanel1,DockState.DockBottom);

        }

        private void SaveConfig()
        {
            retry:
            try
            {
                foreach (var item in dockPanel1.Contents)
                {
                    if (item.GetType() == typeof(FrmFLowChartEdit))
                    {
                        item.DockHandler.Close();//关掉编辑窗口，以便保存IDE配置
                    }
                }
            }
            catch (Exception)
            {
                goto retry;
            }

            _configFile = Path.Combine(Path.GetDirectoryName(Application.ExecutablePath), "DockPanel.config");
            dockPanel1.SaveAsXml(_configFile);
        }

        #endregion

        #region 文档操作区

        private void ShowEditPanel(Flow flow)
        {
            Form selectForm = null;
            foreach (var document in dockPanel1.Documents)
            {
                var frm = document.DockHandler.Form;
                if (frm.Text!=flow.Name) continue;
                selectForm = frm;
                if (dockPanel1.ActiveDocument.DockHandler.Form.Text==flow.Name) return;
                break;
            }
            selectForm?.Close();
            var frmEdit = _container.Resolve<FrmFLowChartEdit>();
            _currentFlow = flow;
            frmEdit.Text = flow.Name;
            frmEdit.LoadFlow(flow);
            frmEdit.Show(dockPanel1);           
        }
        #endregion
    }
}
